var express = require('express');
var router = express.Router();
const querySql = require('../db/index');
const { PWD_SALT,PRIVATE_KEY, EXPIRESD } = require("../utils/constant")
const { md5 } = require('../utils/index')
const jwt = require('jsonwebtoken')
/* GET users listing. */

// 注册用户
router.post('/regist', function(req, res, next) {
  let {username,password} = req.body;
  querySql('SELECT * FROM users WHERE user_name = ?',[username]).then(data => {
  
    if(!data || data.length === 0){
      console.log(2);
      password = md5(`${password}${PWD_SALT}`);
      querySql('INSERT INTO users(user_name,password) value(?,?)',[username,password]).then(result => {
        res.send({code:200,msg:'注册成功',})
      }).catch(err => {
        console.log(err);
        res.send({code:-1,msg:'注册失败'})
      })
    }else{
      res.send({code:-1,msg:'该账号已注册'});
      
    }
  })
});

// 用户登录
router.post('/login',function(req,res,next){
  let { username, password } = req.body;
  password = md5(`${password}${PWD_SALT}`);
  querySql(`SELECT user_name, password FROM users WHERE user_name = ? AND password = ?`,[username,password]).then(data => {
    console.log(data,'data');
    if(!data || data.length === 0){
      res.send({code:-1,msg:'账号密码错误'})
    }else{
      let token = jwt.sign({username},PRIVATE_KEY,{expiresIn:EXPIRESD})
      res.send({code:200,msg:'登陆成功',token})
    }
  }).catch((err) => {
    console.log(err,'err');
    res.send({code:-1,msg:'登录失败'})
  })
})

module.exports = router;
